package com.tqw.chd.service;

import com.tqw.chd.vo.ImageVO;
import jdk.nashorn.internal.parser.DateParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Alex
 */
@Service
public class FileServiceImpl implements FileService{

    //定义根目录
    private String preFilePath = "D:/test_image";

    //定义网络地址前缀
    private String PreURLPath = "http://image.tqw.com";

    /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ImageVO upload(MultipartFile file) {

        //校验文件名
        String fileName = file .getOriginalFilename().toLowerCase();
        if (!fileName.matches("^.+\\.(png|jpg|gif)$")){
            return null;
        }

        //校验是否为恶意程序
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if (height==0 || width==0){
                return null;
            }

            //分目录储存,提高检索效率 按照时间将目录划分 /yyyy/MM/dd/
            String datepath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //拼接目录路径 D:/test_image/yyyy/MM/dd/
            String fileDir = preFilePath + datepath;
            //创建目录
            File dir = new File(fileDir);
            if (!dir.exists()){
                dir.mkdirs();
            }

            //使用uuid作为文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            int index = fileName.lastIndexOf(".");
            //获取图片的类型
            String fileType = fileName.substring(index);
            //拼接新的文件名
            fileName = uuid+fileType;

            //实现文件上传
            String filePath = dir+fileName;
            file.transferTo(new File(filePath));

            //封装ImageVO返回数据
            String virtuaPath=datepath+fileName;
            String urlPath = PreURLPath+virtuaPath;
            return new ImageVO(virtuaPath,urlPath,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除图片
     * @param virtualPath
     */
    @Override
    @Transactional
    public void deleteFile(String virtualPath) {
        String fileURI = preFilePath+virtualPath;
        File image = new File(fileURI);
        if (image.exists()){
            image.delete();
        }
    }
}
